__init__.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. import os
  2. import re
  3. import abc
  4. import csv
  5. import sys
  6. import zipp
  7. import email
  8. import pathlib
  9. import operator
  10. import textwrap
  11. import warnings
  12. import functools
  13. import itertools
  14. import posixpath
  15. import collections
  16. from . import _adapters, _meta
  17. from ._collections import FreezableDefaultDict, Pair
  18. from ._compat import (
  19. NullFinder,
  20. install,
  21. pypy_partial,
  22. )
  23. from ._functools import method_cache, pass_none
  24. from ._itertools import always_iterable, unique_everseen
  25. from ._meta import PackageMetadata, SimplePath
  26. from contextlib import suppress
  27. from importlib import import_module
  28. from importlib.abc import MetaPathFinder
  29. from itertools import starmap
  30. from typing import List, Mapping, Optional, Union
  31. __all__ = [
  32. 'Distribution',
  33. 'DistributionFinder',
  34. 'PackageMetadata',
  35. 'PackageNotFoundError',
  36. 'distribution',
  37. 'distributions',
  38. 'entry_points',
  39. 'files',
  40. 'metadata',
  41. 'packages_distributions',
  42. 'requires',
  43. 'version',
  44. ]
  45. class PackageNotFoundError(ModuleNotFoundError):
  46. """The package was not found."""
  47. def __str__(self):
  48. return f"No package metadata was found for {self.name}"
  49. @property
  50. def name(self):
  51. (name,) = self.args
  52. return name
  53. class Sectioned:
  54. """
  55. A simple entry point config parser for performance
  56. >>> for item in Sectioned.read(Sectioned._sample):
  57. ... print(item)
  58. Pair(name='sec1', value='# comments ignored')
  59. Pair(name='sec1', value='a = 1')
  60. Pair(name='sec1', value='b = 2')
  61. Pair(name='sec2', value='a = 2')
  62. >>> res = Sectioned.section_pairs(Sectioned._sample)
  63. >>> item = next(res)
  64. >>> item.name
  65. 'sec1'
  66. >>> item.value
  67. Pair(name='a', value='1')
  68. >>> item = next(res)
  69. >>> item.value
  70. Pair(name='b', value='2')
  71. >>> item = next(res)
  72. >>> item.name
  73. 'sec2'
  74. >>> item.value
  75. Pair(name='a', value='2')
  76. >>> list(res)
  77. []
  78. """
  79. _sample = textwrap.dedent(
  80. """
  81. [sec1]
  82. # comments ignored
  83. a = 1
  84. b = 2
  85. [sec2]
  86. a = 2
  87. """
  88. ).lstrip()
  89. @classmethod
  90. def section_pairs(cls, text):
  91. return (
  92. section._replace(value=Pair.parse(section.value))
  93. for section in cls.read(text, filter_=cls.valid)
  94. if section.name is not None
  95. )
  96. @staticmethod
  97. def read(text, filter_=None):
  98. lines = filter(filter_, map(str.strip, text.splitlines()))
  99. name = None
  100. for value in lines:
  101. section_match = value.startswith('[') and value.endswith(']')
  102. if section_match:
  103. name = value.strip('[]')
  104. continue
  105. yield Pair(name, value)
  106. @staticmethod
  107. def valid(line):
  108. return line and not line.startswith('#')
  109. class DeprecatedTuple:
  110. """
  111. Provide subscript item access for backward compatibility.
  112. >>> recwarn = getfixture('recwarn')
  113. >>> ep = EntryPoint(name='name', value='value', group='group')
  114. >>> ep[:]
  115. ('name', 'value', 'group')
  116. >>> ep[0]
  117. 'name'
  118. >>> len(recwarn)
  119. 1
  120. """
  121. _warn = functools.partial(
  122. warnings.warn,
  123. "EntryPoint tuple interface is deprecated. Access members by name.",
  124. DeprecationWarning,
  125. stacklevel=pypy_partial(2),
  126. )
  127. def __getitem__(self, item):
  128. self._warn()
  129. return self._key()[item]
  130. class EntryPoint(DeprecatedTuple):
  131. """An entry point as defined by Python packaging conventions.
  132. See `the packaging docs on entry points
  133. <https://packaging.python.org/specifications/entry-points/>`_
  134. for more information.
  135. >>> ep = EntryPoint(
  136. ... name=None, group=None, value='package.module:attr [extra1, extra2]')
  137. >>> ep.module
  138. 'package.module'
  139. >>> ep.attr
  140. 'attr'
  141. >>> ep.extras
  142. ['extra1', 'extra2']
  143. """
  144. pattern = re.compile(
  145. r'(?P<module>[\w.]+)\s*'
  146. r'(:\s*(?P<attr>[\w.]+)\s*)?'
  147. r'((?P<extras>\[.*\])\s*)?$'
  148. )
  149. """
  150. A regular expression describing the syntax for an entry point,
  151. which might look like:
  152. - module
  153. - package.module
  154. - package.module:attribute
  155. - package.module:object.attribute
  156. - package.module:attr [extra1, extra2]
  157. Other combinations are possible as well.
  158. The expression is lenient about whitespace around the ':',
  159. following the attr, and following any extras.
  160. """
  161. dist: Optional['Distribution'] = None
  162. def __init__(self, name, value, group):
  163. vars(self).update(name=name, value=value, group=group)
  164. def load(self):
  165. """Load the entry point from its definition. If only a module
  166. is indicated by the value, return that module. Otherwise,
  167. return the named object.
  168. """
  169. match = self.pattern.match(self.value)
  170. module = import_module(match.group('module'))
  171. attrs = filter(None, (match.group('attr') or '').split('.'))
  172. return functools.reduce(getattr, attrs, module)
  173. @property
  174. def module(self):
  175. match = self.pattern.match(self.value)
  176. return match.group('module')
  177. @property
  178. def attr(self):
  179. match = self.pattern.match(self.value)
  180. return match.group('attr')
  181. @property
  182. def extras(self):
  183. match = self.pattern.match(self.value)
  184. return re.findall(r'\w+', match.group('extras') or '')
  185. def _for(self, dist):
  186. vars(self).update(dist=dist)
  187. return self
  188. def __iter__(self):
  189. """
  190. Supply iter so one may construct dicts of EntryPoints by name.
  191. """
  192. msg = (
  193. "Construction of dict of EntryPoints is deprecated in "
  194. "favor of EntryPoints."
  195. )
  196. warnings.warn(msg, DeprecationWarning)
  197. return iter((self.name, self))
  198. def matches(self, **params):
  199. """
  200. EntryPoint matches the given parameters.
  201. >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
  202. >>> ep.matches(group='foo')
  203. True
  204. >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
  205. True
  206. >>> ep.matches(group='foo', name='other')
  207. False
  208. >>> ep.matches()
  209. True
  210. >>> ep.matches(extras=['extra1', 'extra2'])
  211. True
  212. >>> ep.matches(module='bing')
  213. True
  214. >>> ep.matches(attr='bong')
  215. True
  216. """
  217. attrs = (getattr(self, param) for param in params)
  218. return all(map(operator.eq, params.values(), attrs))
  219. def _key(self):
  220. return self.name, self.value, self.group
  221. def __lt__(self, other):
  222. return self._key() < other._key()
  223. def __eq__(self, other):
  224. return self._key() == other._key()
  225. def __setattr__(self, name, value):
  226. raise AttributeError("EntryPoint objects are immutable.")
  227. def __repr__(self):
  228. return (
  229. f'EntryPoint(name={self.name!r}, value={self.value!r}, '
  230. f'group={self.group!r})'
  231. )
  232. def __hash__(self):
  233. return hash(self._key())
  234. class DeprecatedList(list):
  235. """
  236. Allow an otherwise immutable object to implement mutability
  237. for compatibility.
  238. >>> recwarn = getfixture('recwarn')
  239. >>> dl = DeprecatedList(range(3))
  240. >>> dl[0] = 1
  241. >>> dl.append(3)
  242. >>> del dl[3]
  243. >>> dl.reverse()
  244. >>> dl.sort()
  245. >>> dl.extend([4])
  246. >>> dl.pop(-1)
  247. 4
  248. >>> dl.remove(1)
  249. >>> dl += [5]
  250. >>> dl + [6]
  251. [1, 2, 5, 6]
  252. >>> dl + (6,)
  253. [1, 2, 5, 6]
  254. >>> dl.insert(0, 0)
  255. >>> dl
  256. [0, 1, 2, 5]
  257. >>> dl == [0, 1, 2, 5]
  258. True
  259. >>> dl == (0, 1, 2, 5)
  260. True
  261. >>> len(recwarn)
  262. 1
  263. """
  264. __slots__ = ()
  265. _warn = functools.partial(
  266. warnings.warn,
  267. "EntryPoints list interface is deprecated. Cast to list if needed.",
  268. DeprecationWarning,
  269. stacklevel=pypy_partial(2),
  270. )
  271. def _wrap_deprecated_method(method_name: str): # type: ignore
  272. def wrapped(self, *args, **kwargs):
  273. self._warn()
  274. return getattr(super(), method_name)(*args, **kwargs)
  275. return method_name, wrapped
  276. locals().update(
  277. map(
  278. _wrap_deprecated_method,
  279. '__setitem__ __delitem__ append reverse extend pop remove '
  280. '__iadd__ insert sort'.split(),
  281. )
  282. )
  283. def __add__(self, other):
  284. if not isinstance(other, tuple):
  285. self._warn()
  286. other = tuple(other)
  287. return self.__class__(tuple(self) + other)
  288. def __eq__(self, other):
  289. if not isinstance(other, tuple):
  290. self._warn()
  291. other = tuple(other)
  292. return tuple(self).__eq__(other)
  293. class EntryPoints(DeprecatedList):
  294. """
  295. An immutable collection of selectable EntryPoint objects.
  296. """
  297. __slots__ = ()
  298. def __getitem__(self, name): # -> EntryPoint:
  299. """
  300. Get the EntryPoint in self matching name.
  301. """
  302. if isinstance(name, int):
  303. warnings.warn(
  304. "Accessing entry points by index is deprecated. "
  305. "Cast to tuple if needed.",
  306. DeprecationWarning,
  307. stacklevel=2,
  308. )
  309. return super().__getitem__(name)
  310. try:
  311. return next(iter(self.select(name=name)))
  312. except StopIteration:
  313. raise KeyError(name)
  314. def select(self, **params):
  315. """
  316. Select entry points from self that match the
  317. given parameters (typically group and/or name).
  318. """
  319. return EntryPoints(ep for ep in self if ep.matches(**params))
  320. @property
  321. def names(self):
  322. """
  323. Return the set of all names of all entry points.
  324. """
  325. return {ep.name for ep in self}
  326. @property
  327. def groups(self):
  328. """
  329. Return the set of all groups of all entry points.
  330. For coverage while SelectableGroups is present.
  331. >>> EntryPoints().groups
  332. set()
  333. """
  334. return {ep.group for ep in self}
  335. @classmethod
  336. def _from_text_for(cls, text, dist):
  337. return cls(ep._for(dist) for ep in cls._from_text(text))
  338. @staticmethod
  339. def _from_text(text):
  340. return (
  341. EntryPoint(name=item.value.name, value=item.value.value, group=item.name)
  342. for item in Sectioned.section_pairs(text or '')
  343. )
  344. class Deprecated:
  345. """
  346. Compatibility add-in for mapping to indicate that
  347. mapping behavior is deprecated.
  348. >>> recwarn = getfixture('recwarn')
  349. >>> class DeprecatedDict(Deprecated, dict): pass
  350. >>> dd = DeprecatedDict(foo='bar')
  351. >>> dd.get('baz', None)
  352. >>> dd['foo']
  353. 'bar'
  354. >>> list(dd)
  355. ['foo']
  356. >>> list(dd.keys())
  357. ['foo']
  358. >>> 'foo' in dd
  359. True
  360. >>> list(dd.values())
  361. ['bar']
  362. >>> len(recwarn)
  363. 1
  364. """
  365. _warn = functools.partial(
  366. warnings.warn,
  367. "SelectableGroups dict interface is deprecated. Use select.",
  368. DeprecationWarning,
  369. stacklevel=pypy_partial(2),
  370. )
  371. def __getitem__(self, name):
  372. self._warn()
  373. return super().__getitem__(name)
  374. def get(self, name, default=None):
  375. self._warn()
  376. return super().get(name, default)
  377. def __iter__(self):
  378. self._warn()
  379. return super().__iter__()
  380. def __contains__(self, *args):
  381. self._warn()
  382. return super().__contains__(*args)
  383. def keys(self):
  384. self._warn()
  385. return super().keys()
  386. def values(self):
  387. self._warn()
  388. return super().values()
  389. class SelectableGroups(Deprecated, dict):
  390. """
  391. A backward- and forward-compatible result from
  392. entry_points that fully implements the dict interface.
  393. """
  394. @classmethod
  395. def load(cls, eps):
  396. by_group = operator.attrgetter('group')
  397. ordered = sorted(eps, key=by_group)
  398. grouped = itertools.groupby(ordered, by_group)
  399. return cls((group, EntryPoints(eps)) for group, eps in grouped)
  400. @property
  401. def _all(self):
  402. """
  403. Reconstruct a list of all entrypoints from the groups.
  404. """
  405. groups = super(Deprecated, self).values()
  406. return EntryPoints(itertools.chain.from_iterable(groups))
  407. @property
  408. def groups(self):
  409. return self._all.groups
  410. @property
  411. def names(self):
  412. """
  413. for coverage:
  414. >>> SelectableGroups().names
  415. set()
  416. """
  417. return self._all.names
  418. def select(self, **params):
  419. if not params:
  420. return self
  421. return self._all.select(**params)
  422. class PackagePath(pathlib.PurePosixPath):
  423. """A reference to a path in a package"""
  424. def read_text(self, encoding='utf-8'):
  425. with self.locate().open(encoding=encoding) as stream:
  426. return stream.read()
  427. def read_binary(self):
  428. with self.locate().open('rb') as stream:
  429. return stream.read()
  430. def locate(self):
  431. """Return a path-like object for this path"""
  432. return self.dist.locate_file(self)
  433. class FileHash:
  434. def __init__(self, spec):
  435. self.mode, _, self.value = spec.partition('=')
  436. def __repr__(self):
  437. return f'<FileHash mode: {self.mode} value: {self.value}>'
  438. class Distribution:
  439. """A Python distribution package."""
  440. @abc.abstractmethod
  441. def read_text(self, filename):
  442. """Attempt to load metadata file given by the name.
  443. :param filename: The name of the file in the distribution info.
  444. :return: The text if found, otherwise None.
  445. """
  446. @abc.abstractmethod
  447. def locate_file(self, path):
  448. """
  449. Given a path to a file in this distribution, return a path
  450. to it.
  451. """
  452. @classmethod
  453. def from_name(cls, name):
  454. """Return the Distribution for the given package name.
  455. :param name: The name of the distribution package to search for.
  456. :return: The Distribution instance (or subclass thereof) for the named
  457. package, if found.
  458. :raises PackageNotFoundError: When the named package's distribution
  459. metadata cannot be found.
  460. """
  461. for resolver in cls._discover_resolvers():
  462. dists = resolver(DistributionFinder.Context(name=name))
  463. dist = next(iter(dists), None)
  464. if dist is not None:
  465. return dist
  466. else:
  467. raise PackageNotFoundError(name)
  468. @classmethod
  469. def discover(cls, **kwargs):
  470. """Return an iterable of Distribution objects for all packages.
  471. Pass a ``context`` or pass keyword arguments for constructing
  472. a context.
  473. :context: A ``DistributionFinder.Context`` object.
  474. :return: Iterable of Distribution objects for all packages.
  475. """
  476. context = kwargs.pop('context', None)
  477. if context and kwargs:
  478. raise ValueError("cannot accept context and kwargs")
  479. context = context or DistributionFinder.Context(**kwargs)
  480. return itertools.chain.from_iterable(
  481. resolver(context) for resolver in cls._discover_resolvers()
  482. )
  483. @staticmethod
  484. def at(path):
  485. """Return a Distribution for the indicated metadata path
  486. :param path: a string or path-like object
  487. :return: a concrete Distribution instance for the path
  488. """
  489. return PathDistribution(pathlib.Path(path))
  490. @staticmethod
  491. def _discover_resolvers():
  492. """Search the meta_path for resolvers."""
  493. declared = (
  494. getattr(finder, 'find_distributions', None) for finder in sys.meta_path
  495. )
  496. return filter(None, declared)
  497. @property
  498. def metadata(self) -> _meta.PackageMetadata:
  499. """Return the parsed metadata for this Distribution.
  500. The returned object will have keys that name the various bits of
  501. metadata. See PEP 566 for details.
  502. """
  503. text = (
  504. self.read_text('METADATA')
  505. or self.read_text('PKG-INFO')
  506. # This last clause is here to support old egg-info files. Its
  507. # effect is to just end up using the PathDistribution's self._path
  508. # (which points to the egg-info file) attribute unchanged.
  509. or self.read_text('')
  510. )
  511. return _adapters.Message(email.message_from_string(text))
  512. @property
  513. def name(self):
  514. """Return the 'Name' metadata for the distribution package."""
  515. return self.metadata['Name']
  516. @property
  517. def _normalized_name(self):
  518. """Return a normalized version of the name."""
  519. return Prepared.normalize(self.name)
  520. @property
  521. def version(self):
  522. """Return the 'Version' metadata for the distribution package."""
  523. return self.metadata['Version']
  524. @property
  525. def entry_points(self):
  526. return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)
  527. @property
  528. def files(self):
  529. """Files in this distribution.
  530. :return: List of PackagePath for this distribution or None
  531. Result is `None` if the metadata file that enumerates files
  532. (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is
  533. missing.
  534. Result may be empty if the metadata exists but is empty.
  535. """
  536. def make_file(name, hash=None, size_str=None):
  537. result = PackagePath(name)
  538. result.hash = FileHash(hash) if hash else None
  539. result.size = int(size_str) if size_str else None
  540. result.dist = self
  541. return result
  542. @pass_none
  543. def make_files(lines):
  544. return list(starmap(make_file, csv.reader(lines)))
  545. return make_files(self._read_files_distinfo() or self._read_files_egginfo())
  546. def _read_files_distinfo(self):
  547. """
  548. Read the lines of RECORD
  549. """
  550. text = self.read_text('RECORD')
  551. return text and text.splitlines()
  552. def _read_files_egginfo(self):
  553. """
  554. SOURCES.txt might contain literal commas, so wrap each line
  555. in quotes.
  556. """
  557. text = self.read_text('SOURCES.txt')
  558. return text and map('"{}"'.format, text.splitlines())
  559. @property
  560. def requires(self):
  561. """Generated requirements specified for this Distribution"""
  562. reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()
  563. return reqs and list(reqs)
  564. def _read_dist_info_reqs(self):
  565. return self.metadata.get_all('Requires-Dist')
  566. def _read_egg_info_reqs(self):
  567. source = self.read_text('requires.txt')
  568. return pass_none(self._deps_from_requires_text)(source)
  569. @classmethod
  570. def _deps_from_requires_text(cls, source):
  571. return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))
  572. @staticmethod
  573. def _convert_egg_info_reqs_to_simple_reqs(sections):
  574. """
  575. Historically, setuptools would solicit and store 'extra'
  576. requirements, including those with environment markers,
  577. in separate sections. More modern tools expect each
  578. dependency to be defined separately, with any relevant
  579. extras and environment markers attached directly to that
  580. requirement. This method converts the former to the
  581. latter. See _test_deps_from_requires_text for an example.
  582. """
  583. def make_condition(name):
  584. return name and f'extra == "{name}"'
  585. def quoted_marker(section):
  586. section = section or ''
  587. extra, sep, markers = section.partition(':')
  588. if extra and markers:
  589. markers = f'({markers})'
  590. conditions = list(filter(None, [markers, make_condition(extra)]))
  591. return '; ' + ' and '.join(conditions) if conditions else ''
  592. def url_req_space(req):
  593. """
  594. PEP 508 requires a space between the url_spec and the quoted_marker.
  595. Ref python/importlib_metadata#357.
  596. """
  597. # '@' is uniquely indicative of a url_req.
  598. return ' ' * ('@' in req)
  599. for section in sections:
  600. space = url_req_space(section.value)
  601. yield section.value + space + quoted_marker(section.name)
  602. class DistributionFinder(MetaPathFinder):
  603. """
  604. A MetaPathFinder capable of discovering installed distributions.
  605. """
  606. class Context:
  607. """
  608. Keyword arguments presented by the caller to
  609. ``distributions()`` or ``Distribution.discover()``
  610. to narrow the scope of a search for distributions
  611. in all DistributionFinders.
  612. Each DistributionFinder may expect any parameters
  613. and should attempt to honor the canonical
  614. parameters defined below when appropriate.
  615. """
  616. name = None
  617. """
  618. Specific name for which a distribution finder should match.
  619. A name of ``None`` matches all distributions.
  620. """
  621. def __init__(self, **kwargs):
  622. vars(self).update(kwargs)
  623. @property
  624. def path(self):
  625. """
  626. The sequence of directory path that a distribution finder
  627. should search.
  628. Typically refers to Python installed package paths such as
  629. "site-packages" directories and defaults to ``sys.path``.
  630. """
  631. return vars(self).get('path', sys.path)
  632. @abc.abstractmethod
  633. def find_distributions(self, context=Context()):
  634. """
  635. Find distributions.
  636. Return an iterable of all Distribution instances capable of
  637. loading the metadata for packages matching the ``context``,
  638. a DistributionFinder.Context instance.
  639. """
  640. class FastPath:
  641. """
  642. Micro-optimized class for searching a path for
  643. children.
  644. >>> FastPath('').children()
  645. ['...']
  646. """
  647. @functools.lru_cache() # type: ignore
  648. def __new__(cls, root):
  649. return super().__new__(cls)
  650. def __init__(self, root):
  651. self.root = root
  652. def joinpath(self, child):
  653. return pathlib.Path(self.root, child)
  654. def children(self):
  655. with suppress(Exception):
  656. return os.listdir(self.root or '.')
  657. with suppress(Exception):
  658. return self.zip_children()
  659. return []
  660. def zip_children(self):
  661. zip_path = zipp.Path(self.root)
  662. names = zip_path.root.namelist()
  663. self.joinpath = zip_path.joinpath
  664. return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)
  665. def search(self, name):
  666. return self.lookup(self.mtime).search(name)
  667. @property
  668. def mtime(self):
  669. with suppress(OSError):
  670. return os.stat(self.root).st_mtime
  671. self.lookup.cache_clear()
  672. @method_cache
  673. def lookup(self, mtime):
  674. return Lookup(self)
  675. class Lookup:
  676. def __init__(self, path: FastPath):
  677. base = os.path.basename(path.root).lower()
  678. base_is_egg = base.endswith(".egg")
  679. self.infos = FreezableDefaultDict(list)
  680. self.eggs = FreezableDefaultDict(list)
  681. for child in path.children():
  682. low = child.lower()
  683. if low.endswith((".dist-info", ".egg-info")):
  684. # rpartition is faster than splitext and suitable for this purpose.
  685. name = low.rpartition(".")[0].partition("-")[0]
  686. normalized = Prepared.normalize(name)
  687. self.infos[normalized].append(path.joinpath(child))
  688. elif base_is_egg and low == "egg-info":
  689. name = base.rpartition(".")[0].partition("-")[0]
  690. legacy_normalized = Prepared.legacy_normalize(name)
  691. self.eggs[legacy_normalized].append(path.joinpath(child))
  692. self.infos.freeze()
  693. self.eggs.freeze()
  694. def search(self, prepared):
  695. infos = (
  696. self.infos[prepared.normalized]
  697. if prepared
  698. else itertools.chain.from_iterable(self.infos.values())
  699. )
  700. eggs = (
  701. self.eggs[prepared.legacy_normalized]
  702. if prepared
  703. else itertools.chain.from_iterable(self.eggs.values())
  704. )
  705. return itertools.chain(infos, eggs)
  706. class Prepared:
  707. """
  708. A prepared search for metadata on a possibly-named package.
  709. """
  710. normalized = None
  711. legacy_normalized = None
  712. def __init__(self, name):
  713. self.name = name
  714. if name is None:
  715. return
  716. self.normalized = self.normalize(name)
  717. self.legacy_normalized = self.legacy_normalize(name)
  718. @staticmethod
  719. def normalize(name):
  720. """
  721. PEP 503 normalization plus dashes as underscores.
  722. """
  723. return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_')
  724. @staticmethod
  725. def legacy_normalize(name):
  726. """
  727. Normalize the package name as found in the convention in
  728. older packaging tools versions and specs.
  729. """
  730. return name.lower().replace('-', '_')
  731. def __bool__(self):
  732. return bool(self.name)
  733. @install
  734. class MetadataPathFinder(NullFinder, DistributionFinder):
  735. """A degenerate finder for distribution packages on the file system.
  736. This finder supplies only a find_distributions() method for versions
  737. of Python that do not have a PathFinder find_distributions().
  738. """
  739. def find_distributions(self, context=DistributionFinder.Context()):
  740. """
  741. Find distributions.
  742. Return an iterable of all Distribution instances capable of
  743. loading the metadata for packages matching ``context.name``
  744. (or all names if ``None`` indicated) along the paths in the list
  745. of directories ``context.path``.
  746. """
  747. found = self._search_paths(context.name, context.path)
  748. return map(PathDistribution, found)
  749. @classmethod
  750. def _search_paths(cls, name, paths):
  751. """Find metadata directories in paths heuristically."""
  752. prepared = Prepared(name)
  753. return itertools.chain.from_iterable(
  754. path.search(prepared) for path in map(FastPath, paths)
  755. )
  756. def invalidate_caches(cls):
  757. FastPath.__new__.cache_clear()
  758. class PathDistribution(Distribution):
  759. def __init__(self, path: SimplePath):
  760. """Construct a distribution.
  761. :param path: SimplePath indicating the metadata directory.
  762. """
  763. self._path = path
  764. def read_text(self, filename):
  765. with suppress(
  766. FileNotFoundError,
  767. IsADirectoryError,
  768. KeyError,
  769. NotADirectoryError,
  770. PermissionError,
  771. ):
  772. return self._path.joinpath(filename).read_text(encoding='utf-8')
  773. read_text.__doc__ = Distribution.read_text.__doc__
  774. def locate_file(self, path):
  775. return self._path.parent / path
  776. @property
  777. def _normalized_name(self):
  778. """
  779. Performance optimization: where possible, resolve the
  780. normalized name from the file system path.
  781. """
  782. stem = os.path.basename(str(self._path))
  783. return self._name_from_stem(stem) or super()._normalized_name
  784. def _name_from_stem(self, stem):
  785. name, ext = os.path.splitext(stem)
  786. if ext not in ('.dist-info', '.egg-info'):
  787. return
  788. name, sep, rest = stem.partition('-')
  789. return name
  790. def distribution(distribution_name):
  791. """Get the ``Distribution`` instance for the named package.
  792. :param distribution_name: The name of the distribution package as a string.
  793. :return: A ``Distribution`` instance (or subclass thereof).
  794. """
  795. return Distribution.from_name(distribution_name)
  796. def distributions(**kwargs):
  797. """Get all ``Distribution`` instances in the current environment.
  798. :return: An iterable of ``Distribution`` instances.
  799. """
  800. return Distribution.discover(**kwargs)
  801. def metadata(distribution_name) -> _meta.PackageMetadata:
  802. """Get the metadata for the named package.
  803. :param distribution_name: The name of the distribution package to query.
  804. :return: A PackageMetadata containing the parsed metadata.
  805. """
  806. return Distribution.from_name(distribution_name).metadata
  807. def version(distribution_name):
  808. """Get the version string for the named package.
  809. :param distribution_name: The name of the distribution package to query.
  810. :return: The version string for the package as defined in the package's
  811. "Version" metadata key.
  812. """
  813. return distribution(distribution_name).version
  814. def entry_points(**params) -> Union[EntryPoints, SelectableGroups]:
  815. """Return EntryPoint objects for all installed packages.
  816. Pass selection parameters (group or name) to filter the
  817. result to entry points matching those properties (see
  818. EntryPoints.select()).
  819. For compatibility, returns ``SelectableGroups`` object unless
  820. selection parameters are supplied. In the future, this function
  821. will return ``EntryPoints`` instead of ``SelectableGroups``
  822. even when no selection parameters are supplied.
  823. For maximum future compatibility, pass selection parameters
  824. or invoke ``.select`` with parameters on the result.
  825. :return: EntryPoints or SelectableGroups for all installed packages.
  826. """
  827. norm_name = operator.attrgetter('_normalized_name')
  828. unique = functools.partial(unique_everseen, key=norm_name)
  829. eps = itertools.chain.from_iterable(
  830. dist.entry_points for dist in unique(distributions())
  831. )
  832. return SelectableGroups.load(eps).select(**params)
  833. def files(distribution_name):
  834. """Return a list of files for the named package.
  835. :param distribution_name: The name of the distribution package to query.
  836. :return: List of files composing the distribution.
  837. """
  838. return distribution(distribution_name).files
  839. def requires(distribution_name):
  840. """
  841. Return a list of requirements for the named package.
  842. :return: An iterator of requirements, suitable for
  843. packaging.requirement.Requirement.
  844. """
  845. return distribution(distribution_name).requires
  846. def packages_distributions() -> Mapping[str, List[str]]:
  847. """
  848. Return a mapping of top-level packages to their
  849. distributions.
  850. >>> import collections.abc
  851. >>> pkgs = packages_distributions()
  852. >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())
  853. True
  854. """
  855. pkg_to_dist = collections.defaultdict(list)
  856. for dist in distributions():
  857. for pkg in _top_level_declared(dist) or _top_level_inferred(dist):
  858. pkg_to_dist[pkg].append(dist.metadata['Name'])
  859. return dict(pkg_to_dist)
  860. def _top_level_declared(dist):
  861. return (dist.read_text('top_level.txt') or '').split()
  862. def _top_level_inferred(dist):
  863. return {
  864. f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name
  865. for f in always_iterable(dist.files)
  866. if f.suffix == ".py"
  867. }